﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.DataModel;
using YArchitech.HVAC;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class HYPipeConnectFixtures : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			Selection selection = activeUIDocument.Selection;
			if (!YJKRevitTools.ViewCheck(activeUIDocument, new List<ViewType>
			{
				(ViewType)1,
				(ViewType)2
			}))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			ISelectionFilter pipingAndEquipmentFilter = new PipeAndFixturesFilter();
			ISelectionFilter pipingFilter = new HoriPipeFilter();
			ISelectionFilter equipmentFilter = new FixturesFilter();
			SetTrapForm setTrapForm = new SetTrapForm();
			int num = 0;
			HYPipeConnectFixtures.hWndRevit = new YJKWindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			setTrapForm.Show(HYPipeConnectFixtures.hWndRevit);
			int wMsg = 7;
			HYPipeConnectFixtures.SendMessage(HYPipeConnectFixtures.hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			Result result;
			for (;;)
			{
				Transaction transaction = null;
				try
				{
					if (num != 0)
					{
						RevitVersionFuncs.ClearSelection(selection);
					}
					num++;
					List<Pipe> list = new List<Pipe>();
					Pipe pipe = null;
					List<FamilyInstance> list2 = new List<FamilyInstance>();
					SelectionTypePara selectionTypePara = new SelectionTypePara(BuiltInCategory.OST_PipeCurves, BuiltInCategory.OST_PlumbingFixtures, pipingFilter, equipmentFilter, pipingAndEquipmentFilter, "请框选水管", "请框选卫生设备", "请框选水管和卫生设备");
					List<Element> list3 = RevitAPIUIOperate.SelectionCheck(document, selection, selectionTypePara, true);
					int num2 = 0;
					int num3 = 0;
					foreach (Element element in list3)
					{
						if (element is Pipe)
						{
							list.Add(element as Pipe);
							num3++;
						}
						else if (element is FamilyInstance)
						{
							list2.Add(element as FamilyInstance);
							num2++;
						}
					}
					transaction = new Transaction(document, "水管连接器具");
					transaction.Start();
					if (list2.Count >= 1 || list.Count >= 1)
					{
						if (list2.Count < 1 || list.Count < 1)
						{
							YJKMessageBox.Information("至少选择一个卫生设备和水平管道！");
						}
						else
						{
							int num4 = 0;
							int num5 = 0;
							foreach (Pipe pipe2 in list)
							{
								PipeSystemType systemType = (pipe2.MEPSystem as PipingSystem).SystemType;
                                if (16 == (int)systemType)
								{
									num4++;
								}
							}
							foreach (Pipe pipe3 in list)
							{
								PipeSystemType systemType2 = (pipe3.MEPSystem as PipingSystem).SystemType;
                                if (20 == (int)systemType2)
								{
									num5++;
								}
							}
							if (num4 > 1 || num5 > 1)
							{
								YJKMessageBox.Information("所选管道太多，请重新选择");
								transaction.RollBack();
								continue;
							}
							foreach (Pipe pipe4 in list)
							{
								PipeSystemType systemType3 = (pipe4.MEPSystem as PipingSystem).SystemType;
                                if (16 == (int)systemType3)
								{
									pipe = pipe4;
									list.Remove(pipe4);
									break;
								}
							}
							string msg = "";
							HYErrorMessage hyerrorMessage = new HYErrorMessage(msg);
							if (pipe != null)
							{
								AutoDesignHelper autoDesignHelper = new AutoDesignHelper();
								FamilySymbol familySymbolByName = YJKRevitTools.GetFamilySymbolByName("Fitting", "顺水三通", document, ref msg);
								hyerrorMessage.AddMessage(msg);
								bool is45Elbow = true;
								HVACUserSetting hvacuserSetting = new HVACUserSetting();
								FamilySymbol fsBend = null;
								string connectTrapText = hvacuserSetting.GetConnectTrapText();
								if (!(connectTrapText == "0"))
								{
									if (!(connectTrapText == "1"))
									{
										if (connectTrapText == "2")
										{
											fsBend = null;
										}
									}
									else
									{
										fsBend = YJKRevitTools.GetFamilySymbolByName("Fitting", "180°P型存水弯", document, ref msg);
										hyerrorMessage.AddMessage(msg);
									}
								}
								else
								{
									fsBend = YJKRevitTools.GetFamilySymbolByName("Fitting", "180°S型存水弯", document, ref msg);
									hyerrorMessage.AddMessage(msg);
								}
								autoDesignHelper.PipeConnectEquipmentBatch(list2, pipe, familySymbolByName, fsBend, is45Elbow, ref msg);
								hyerrorMessage.AddMessage(msg);
							}
							bool flag = true;
							if (list.Count > 0)
							{
								flag = new HYPipeConnect().NewBeatchPipeEquipment(list2, list, 0);
								if (!flag)
								{
									msg = "管道系统分类不匹配";
									hyerrorMessage.AddMessage(msg);
								}
							}
							if (hyerrorMessage.AddMessage(msg) != "")
							{
								hyerrorMessage.ShowMessage("information");
							}
							else if (!flag)
							{
								YJKMessageBox.Information("部分器具连接失败，请检查");
							}
						}
					}
					RevitVersionFuncs.ClearSelection(selection);
					document.Regenerate();
					transaction.Commit();
					continue;
				}
				catch (Autodesk.Revit.Exceptions.OperationCanceledException)
				{
					setTrapForm.Close();
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
				catch (Exception ex)
				{
					if (!ex.ToString().Contains("外部组件发生异常"))
					{
						YJKMessageBox.Error(ex.Message);
						continue;
					}
					setTrapForm.Close();
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
				finally
				{
					if (transaction != null && (int)transaction.GetStatus() != 3 && (int)transaction.GetStatus() != 2)
					{
						transaction.RollBack();
					}
				}
				break;
			}
			return result;
		}

		public static YJKWindowHandle hWndRevit;
	}
}
